/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.generalfile.servlet;

import cn.net.greenet.common.db_service.ConfigManager;
import cn.net.greenet.common.policy_service.PolicySupport;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Hfub;
import cn.net.greenet.generalfile.logic.GeneralFileProcess;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * 读取用户上传的HTTP Get报文清洗url黑名单文件入库
 *
 * @author ShiYun,2014/11/04
 */
@WebServlet(name = "GetUrlBlack2DB", urlPatterns = {"/common/read_black_url_list"})
public class GetUrlBlack2DB extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String path = request.getParameter("path");
        String MessageType = request.getParameter("MessageType");
        String policy_instance = request.getParameter("policy_instance");

        boolean result = false;
//        JSONObject one = new JSONObject();
        GeneralFileProcess pro = new GeneralFileProcess(path, MessageType, policy_instance);
        String name = ConfigManager.getInstance().getString("urlBlackFileName");
        path = pro.saveFile(request, name);
        if (path != null) {
//            String sql = GeneralFileProcess.INSERT_URL_BLACK;
            List<String> list = pro.getContent(path, 1);
            if (!list.isEmpty()) {
                SessionFactory sf = HibernateUtil.getSessionFactory();
                Session session = sf.openSession();
                session.clear();
                Transaction tx = session.beginTransaction();
                String hql = "from Hfub";
                List hfubs = session.createQuery(hql).list();
                Map<String, Integer> map = new HashMap<String, Integer>();
                if (!hfubs.isEmpty()) {
                    for (int i = 0; i < hfubs.size(); i++) {
                        Hfub h = (Hfub) hfubs.get(i);
                        map.put(h.getFilter(), h.getId());
                    }
                }
                Hfub hfub = null;
                try {
                    for (String line : list) {
                        String[] ss = line.split("\t");
                        String url = ss[0];
                        if (!map.containsKey(url)) {
                            hfub = new Hfub(url);
                            session.save(hfub);
                            int id = map.size()+1;
                            map.put(url, id);
                        }
                    }
                    tx.commit();
                    result = true;
                } catch (Exception e) {
                    tx.rollback();
                    result = false;
                } finally {
                    session.close();
                }
                try {
                    PolicySupport policySupport = PolicySupport.getInstance();
                    String policy = policySupport.getApi().getMessage("0xCF", "默认库", 0).getSvnFile().getContent();
                    String comment = policySupport.getApi().getMessage("0xCF", "默认库", 0).getSvnFile().getComment();
                    policySupport.getApi().updatePolicy("0xCF", "默认库", 0, policy, comment);
                } catch (Exception e) {
                }

                // 获取数据库链接
//                pro.init();
//                for (String line : list) {
//                    String[] ss = line.split("\t");
//                    pro.insert(sql, ss);
//                }
//                result = true;
                //关闭数据库链接
//                pro.close();
            }
        }
//        one.put("result", result);
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println(result);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
